package com.zzzyh.forumsystemclient.cotroller;

import com.alibaba.fastjson.JSON;
import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.model.Article;
import com.zzzyh.forumsystemclient.model.LoginUser;
import com.zzzyh.forumsystemclient.model.Moment;
import com.zzzyh.forumsystemclient.model.PageResult;
import com.zzzyh.forumsystemclient.services.IMomentService;
import com.zzzyh.forumsystemclient.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/moment")
@Slf4j
public class MomentController {
    @Autowired
    private IMomentService momentService;
    @RequestMapping("/list")
    public AppResult<PageResult<Moment>> list(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                                              @RequestHeader("Authorization") String token){
        LoginUser user = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
        Integer userId = user.getUser().getId();
        List<Moment> moments = momentService.list(userId,pageNum, pageSize);
        Integer total = momentService.total(userId);
        if (pageNum == 1 && pageSize == 5) {
            // 将<img>标签切换为[图片]简化展示 并且只展示一行的有效信息
            for (Moment moment : moments){
                String content = moment.getContent();
                if (content.contains("<img")){
                    content = content.replaceAll("<img.*?>", "[图片]");
                }
                // 处理HTML格式，提取第一行内容
                if (content.contains("</p>")) {
                    int endIndex = content.indexOf("</p>");
                    content = content.substring(0, endIndex + 4); // 保留完整的第一个<p>标签
                }
                moment.setContent(content);
            }
        }
        PageResult<Moment> pageResult = new PageResult<>(pageNum, pageSize,total ,moments);
        return AppResult.success(pageResult);
    }
    @RequestMapping("/publish")
    public AppResult<String> publish(@RequestBody Moment moment,
                                    @RequestHeader("Authorization") String token){
//        log.info("发布动态: " + moment);
        LoginUser user = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
        Integer userId = user.getUser().getId();
        moment.setUserId(Long.valueOf(userId));
        moment.setCreateTime(new java.util.Date());
        momentService.add(moment);
        return AppResult.success("发布成功");
    }
    @RequestMapping("/updateTalkApi")
    public AppResult<String> updateTalkApi(@RequestBody Moment moment){
//        log.info("更新动态: " + moment);
        momentService.update(moment);
        return AppResult.success("更新成功");
    }
}
